package com.leetcode.LC_MED;

import java.util.LinkedHashMap;

public class LC146 {
    class LRUCache {
        private int capacity;
        LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();

        public LRUCache(int capacity) {
            this.capacity = capacity;
        }

        public int get(int key) {
            if (map.containsKey(key)) {
                // 保证每次数据查询后都在末端
                int val = map.get(key);
                map.remove(key);
                map.put(key, val);
                return val;
            }
            return -1;
        }

        public void put(int key, int value) {
            if (map.containsKey(key)) {
                // 包含此key，则删除在最后插入
                map.remove(key);
            } else if (map.size() == capacity) {
                // map容量满之后，删除第一个数据
                int firstKey = map.entrySet().iterator().next().getKey();
                map.remove(firstKey);
            }
            // 插入新数据
            map.put(key, value);
        }
    }

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
}
